package yl.hs.bmipfull.service.production.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IRawMaterialInfoDao;
import yl.hs.bmipfull.daos.production.IProductionLinePortDao;
import yl.hs.bmipfull.pojo.material.RawMaterialInfoEntity;
import yl.hs.bmipfull.pojo.production.ProductionLineEntity;
import yl.hs.bmipfull.pojo.production.ProductionLinePortEntity;
import yl.hs.bmipfull.service.production.IProductionLinePortService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作用:  生产线物料口信息表服务层接口实现<br/>
 * 创建时间: 2021年05月25日 15时21分27秒 <br/>
 *
 * @author 张凯
 */
@Service
public class ProductionLinePortServiceImpl extends ProductionBaseService implements IProductionLinePortService {

    @Autowired
    IProductionLinePortDao dao;

    @Autowired
    IRawMaterialInfoDao rmDao;

    @Override
    public List<ProductionLinePortEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(ProductionLinePortEntity.class);
        return dao.queryList(pageQuery.getQuery());
    }

    @Override
    public PageResult<Object> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(ProductionLinePortEntity.class, "sortCode ASC");
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<Object> result = new PageResult(rowNum);
        pageQuery.getQuery().put("unitSNArray", getCompanySNList());
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),ProductionLinePortEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(),filters));
        result.setPage(page);
        var portList = dao.queryPage(pageQuery.getQuery(),filters);
        var rmSNList = portList.stream().map(t -> t.getRmSN()).distinct().collect(Collectors.toList());
        List<RawMaterialInfoEntity> rmList = rmDao.queryListBySnList(rmSNList);
        List<Object> newList = new ArrayList<>();
        for (var port : portList) {
            var portMap = port.toMap();
            var rmInfo = rmList.stream().filter(t -> t.getSn().equals(port.getRmSN())).findFirst();
            var rmName = "";
            if (rmInfo.isPresent()) {
                rmName = Tl.getRawMaterialFullName(rmInfo.get());
            }
            portMap.put("rmName", rmName);
            newList.add(portMap);
        }
        result.setData(newList);
        return result;
    }


    @Override
    public ProductionLinePortEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional
    public Integer saveProductionLinePort(Map<String, Object> model, String sn) throws Exception {
        Integer result = 0;
        ProductionLinePortEntity entity = new ProductionLinePortEntity();
        if (Tl.isEmpty(sn)) {
            //执行保存

            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(ProductionLinePortEntity.class));
            entity.setOrganizationCode(getDepartSN());
            result = dao.insertNew(entity);
            if (result > 0) {
                writeUnitTag(entity.getSn(), ProductionLinePortEntity.class, RelationType.CREATE.toString());
                writeLog(ActionType.CREATE, entity.getSn(), "插入生产线物料口信息表信息", Tl.toJson(entity), ProductionLinePortEntity.class);
                saveGS(
                        entity.getSn(),
                        entity.getPortName(),
                        String.join(",",
                                entity.getPortName(),
                                entity.getPortCode(),
                                entity.getWhName(),
                                entity.getRemark()
                        ),
                        entity,
                        HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                        null
                );
            }

        } else {
            //执行修改
            entity = findBySn(sn);
            var changelog = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setOrganizationCode(getDepartSN());
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, sn, changelog, Tl.toJson(entity), ProductionLinePortEntity.class);
            }
        }
        var rmInfo = rmDao.findBySN(entity.getRmSN());
        var similarRmList = rmDao.queryListByParam(rmInfo.getRmCateSN(), rmInfo.getRmName(), rmInfo.getRmSpec());
        if (similarRmList.size() > 0) {
            var rmList = similarRmList.stream().map(t -> t.getSn()).collect(Collectors.toList());
            var lineSN = entity.getLineSN();
            var similarPortList = dao.queryByRm(lineSN, rmList);
            if (similarPortList.size() > 1) {
                var postOutScale = new BigDecimal(100).subtract(entity.getOutScale()).divide(new BigDecimal(similarPortList.size() - 1));
                for (var port : similarPortList) {
                    if (!port.getSn().equals(entity.getSn())) {
                        port.setOutScale(postOutScale);
                        dao.update(port);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public boolean checkExistsCodePort(String plSN, String portCode, String oldSN) {
        var port = dao.findByPortCode(plSN, portCode, oldSN);
        return port != null;
    }

    @Override
    public Integer changeStateBySn(String[] snArray, short state) {
        int result=dao.changeStateBySn(snArray,state);
        if (result > 0) {
            forWriteLog(snArray,state);
        }
        return result;
    }


    @Override
    public Integer delete(String[] sn) {
        var result = dao.changeStateBySn(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, ProductionLinePortEntity.class);
        }
        return result;
    }

    @Override
    public List<ProductionLinePortEntity> queryListPort(String plSN) {

        return dao.queryListByLineSN(plSN);
    }

}